<?php

namespace support\Middleware\admin;

use support\exception\BusinessException;
use support\Service\MenuService;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AccessControl implements MiddlewareInterface
{
    /**
     * @param Request $request
     * @param callable $handler
     * @return Response
     * @throws BusinessException
     */
    public function process(Request $request, callable $handler): Response
    {
        $path = $request->path();
        $controller = $request->controller;
        if (str_contains($controller, 'LoginController') || str_contains($controller, 'MockController')) {
            return $handler($request);
        }
        if (!$path) {
            return $handler($request);
        }
        if(env('envi') == 'preview'){
            $path_arr=pathinfo($path);
            if(!in_array($path_arr['filename'],['getUserInfo','getMenuList','index','login','logout','getRoles','getRoleList','getPermissionList',
                'loginLog','actionLog','images','statistics','file','valueList','configData','version','setColumn','preview','code','column'])){
                return  error(402, '演示环境！不允许操作');
            }
        }
        try {
            $uid = \Tinywan\Jwt\JwtToken::getCurrentId();
        }catch (\Throwable $e){
            return error(401, '请重新登录');
        }
        $menuService =new MenuService();
        $paths = $menuService->getPermissionsPathList($uid);
        if ($uid != env('SUPER_ADMIN') && (!$paths || !in_array($path, $paths))) {
            $response = error(401, '未经授权');
        } else {
            $response = $handler($request);
        }
        return $response;

    }
}